// Protocol3 示例数据
// 提供协议配置、绑定和测试的示例数据
// 汇总所有迁移的协议数据

import type {
  MerchantChannelConfig3,
  QRCodeConfig,
  DefaultProtocol,
  ProtocolBinding,
  ChannelConfigType
} from '../types/protocol3-types'
import {
  ProtocolType3,
  ProtocolBindingStatus,
  FieldType,
  generateProtocolId,
  generateUniqueId,
  formatTimestamp
} from '../types/protocol3-types'

// 导入迁移的协议数据
import { protocol3ProviderConfigs } from './protocol3-mc-provider'
import { protocol3SubMerchantConfigs } from './protocol3-mc-sub-merchant'
import { protocol3DirectMerchantConfigs } from './protocol3-mc-direct-merchant'
import { protocol3QRCodeConfigs } from './protocol3-qrcode-config'

// 汇总所有商户渠道配置协议
export const sampleMerchantChannelConfigs: MerchantChannelConfig3[] = [
  ...protocol3ProviderConfigs,
  ...protocol3SubMerchantConfigs,
  ...protocol3DirectMerchantConfigs,
  // 原有的示例数据保留作为补充（如果需要）
]

// 汇总所有二维码配置协议
export const sampleQRCodeConfigs: QRCodeConfig[] = [
  ...protocol3QRCodeConfigs,
  // 原有的示例数据保留作为补充（如果需要）
]

// 默认协议配置（兜底协议）
export const sampleDefaultProtocols: DefaultProtocol[] = [
  {
    protocolId: 'DEFAULT_PROTOCOL_FALLBACK_001',
    protocolType: ProtocolType3.DEFAULT_PROTOCOL,
    channelCode: 'DEFAULT',
    name: '默认兜底协议',
    version: '1.0.0',
    description: '当没有匹配的协议时使用的默认兜底协议，确保系统的稳定性和可用性',
    enabled: true,
    fallbackConfig: {
      timeout: 30000,
      retryCount: 3,
      useStandardResponse: true,
      logLevel: 'INFO'
    },
    priority: 999, // 最低优先级，作为兜底使用
    configSections: [
      {
        sectionKey: 'basic_settings',
        sectionName: '基础设置',
        description: '默认协议的基础配置项',
        icon: 'SettingOutlined',
        order: 1,
        collapsed: false,
        fields: [
          {
            fieldKey: 'timeout',
            fieldName: '超时时间(ms)',
            fieldType: FieldType.NUMBER,
            required: true,
            defaultValue: 30000,
            placeholder: '请输入超时时间',
            description: '请求超时时间，单位毫秒',
            validation: {
              required: true,
              min: 1000,
              max: 120000,
              message: '超时时间必须在1秒到2分钟之间'
            }
          },
          {
            fieldKey: 'retryCount',
            fieldName: '重试次数',
            fieldType: FieldType.NUMBER,
            required: true,
            defaultValue: 3,
            placeholder: '请输入重试次数',
            description: '失败时的重试次数',
            validation: {
              required: true,
              min: 0,
              max: 10,
              message: '重试次数必须在0到10之间'
            }
          },
          {
            fieldKey: 'useStandardResponse',
            fieldName: '使用标准响应格式',
            fieldType: FieldType.SWITCH,
            required: false,
            defaultValue: true,
            description: '是否使用标准的响应格式'
          },
          {
            fieldKey: 'logLevel',
            fieldName: '日志级别',
            fieldType: FieldType.SELECT,
            required: true,
            defaultValue: 'INFO',
            placeholder: '请选择日志级别',
            description: '系统日志记录级别',
            options: [
              { label: 'DEBUG', value: 'DEBUG' },
              { label: 'INFO', value: 'INFO' },
              { label: 'WARN', value: 'WARN' },
              { label: 'ERROR', value: 'ERROR' }
            ],
            validation: {
              required: true,
              message: '请选择日志级别'
            }
          }
        ],
        defaultValues: {
          timeout: 30000,
          retryCount: 3,
          useStandardResponse: true,
          logLevel: 'INFO'
        }
      }
    ],
    uiConfig: {
      layout: 'horizontal',
      labelWidth: 120,
      showDescription: true,
      grouping: 'sections'
    },
    metadata: {
      author: 'AnyPay System',
      createTime: formatTimestamp(Date.now()),
      updateTime: formatTimestamp(Date.now()),
      tags: ['默认协议', '兜底', '系统'],
      category: '系统协议',
      documentation: '默认兜底协议用于保证系统在没有匹配协议时的正常运行'
    }
  }
]

// 示例渠道配置类型
export const sampleChannelConfigTypes: ChannelConfigType[] = [
  {
    configType: 'MERCHANT_CONFIG',
    configName: '商户配置',
    channelCode: 'WXPAY',
    channelName: '微信支付',
    description: '微信支付商户配置',
    enabled: true
  },
  {
    configType: 'QR_CODE_CONFIG',
    configName: '二维码配置',
    channelCode: 'WXPAY',
    channelName: '微信支付',
    description: '微信支付二维码配置',
    enabled: true
  },
  {
    configType: 'MERCHANT_CONFIG',
    configName: '商户配置',
    channelCode: 'ALIPAY',
    channelName: '支付宝',
    description: '支付宝商户配置',
    enabled: true
  },
  {
    configType: 'QR_CODE_CONFIG',
    configName: '二维码配置',
    channelCode: 'ALIPAY',
    channelName: '支付宝',
    description: '支付宝二维码配置',
    enabled: true
  },
  {
    configType: 'MERCHANT_CONFIG',
    configName: '商户配置',
    channelCode: 'UNIONPAY',
    channelName: '银联支付',
    description: '银联支付商户配置',
    enabled: true
  },
  {
    configType: 'QR_CODE_CONFIG',
    configName: '二维码配置',
    channelCode: 'UNIONPAY',
    channelName: '银联支付',
    description: '银联支付二维码配置',
    enabled: true
  }
]

// 示例协议绑定
export const sampleProtocolBindings: ProtocolBinding[] = [
  {
    bindingId: generateUniqueId('binding'),
    protocolId: sampleMerchantChannelConfigs[0].protocolId,
    channelCode: 'WXPAY',
    channelName: '微信支付',
    configType: 'MERCHANT_CONFIG',
    status: ProtocolBindingStatus.ACTIVE,
    priority: 1,
    createTime: formatTimestamp(Date.now()),
    updateTime: formatTimestamp(Date.now()),
    description: '微信支付商户配置绑定'
  },
  {
    bindingId: generateUniqueId('binding'),
    protocolId: sampleQRCodeConfigs[0].protocolId,
    channelCode: 'WXPAY',
    channelName: '微信支付',
    configType: 'QR_CODE_CONFIG',
    status: ProtocolBindingStatus.ACTIVE,
    priority: 1,
    createTime: formatTimestamp(Date.now()),
    updateTime: formatTimestamp(Date.now()),
    description: '微信支付二维码配置绑定'
  },
  {
    bindingId: generateUniqueId('binding'),
    protocolId: sampleMerchantChannelConfigs[1].protocolId,
    channelCode: 'ALIPAY',
    channelName: '支付宝',
    configType: 'MERCHANT_CONFIG',
    status: ProtocolBindingStatus.ACTIVE,
    priority: 1,
    createTime: formatTimestamp(Date.now()),
    updateTime: formatTimestamp(Date.now()),
    description: '支付宝商户配置绑定'
  },
  {
    bindingId: generateUniqueId('binding'),
    protocolId: sampleMerchantChannelConfigs[1].protocolId,
    channelCode: 'ALIPAY',
    channelName: '支付宝',
    configType: 'QR_CODE_CONFIG',
    status: ProtocolBindingStatus.PENDING,
    priority: 2,
    createTime: formatTimestamp(Date.now()),
    updateTime: formatTimestamp(Date.now()),
    description: '支付宝二维码配置绑定（待激活）'
  }
]

// 初始化示例数据的函数
export async function initializeSampleData() {
  try {
    // 动态导入protocol3Manager
    const { protocol3Manager } = await import('./protocol3-manager')

    // 添加渠道配置类型（先添加配置类型）
    sampleChannelConfigTypes.forEach(configType => {
      try {
        protocol3Manager.addChannelConfigType(configType)
      } catch (error) {
        console.error('添加渠道配置类型失败:', configType.configName, error)
      }
    })

    // 注册商户渠道配置协议
    sampleMerchantChannelConfigs.forEach((config, index) => {
      try {
        // 验证必要字段
        if (!config.protocolId || !config.name || !config.configSections) {
          console.error('配置缺少必要字段:', config)
          return
        }
        protocol3Manager.registerMerchantChannelConfig(config)
      } catch (error) {
        console.error('✗ 注册商户渠道配置失败:', config.name, error)
      }
    })

    // 注册二维码配置协议
    sampleQRCodeConfigs.forEach((config, index) => {
      try {
        // 验证必要字段
        if (!config.protocolId || !config.name || !config.configSections) {
          console.error('配置缺少必要字段:', config)
          return
        }
        protocol3Manager.registerQRCodeConfig(config)
      } catch (error) {
        console.error('✗ 注册二维码配置失败:', config.name, error)
      }
    })

    // 注册默认协议
    sampleDefaultProtocols.forEach((config, index) => {
      try {
        // 验证必要字段
        if (!config.protocolId || !config.name || !config.configSections) {
          console.error('配置缺少必要字段:', config)
          return
        }
        // 注册默认协议（如果protocol3Manager支持的话）
        if (typeof protocol3Manager.registerDefaultProtocol === 'function') {
          protocol3Manager.registerDefaultProtocol(config)
        } else {
          // 如果没有专门的方法，则将其作为通用协议注册
          protocol3Manager.registerProtocol?.(config)
        }
      } catch (error) {
        console.error('✗ 注册默认协议失败:', config.name, error)
      }
    })

    // 创建协议绑定
    sampleProtocolBindings.forEach(binding => {
      try {
        const { bindingId, createTime, updateTime, ...bindingData } = binding
        protocol3Manager.createProtocolBinding(bindingData)
      } catch (error) {
        console.error('✗ 创建协议绑定失败:', binding.description, error)
      }
    })

    const totalProtocols = protocol3Manager.getAllProtocols().length

    if (totalProtocols === 0) {
      console.error('警告: 没有任何协议被成功注册！')
    }

  } catch (error) {
    console.error('初始化Protocol3示例数据失败:', error)
  }
}

// 默认导出
export default {
  sampleMerchantChannelConfigs,
  sampleQRCodeConfigs,
  sampleDefaultProtocols,
  sampleChannelConfigTypes,
  sampleProtocolBindings,
  initializeSampleData
}